package com.study.forumsystemproject.controller;
import com.study.forumsystemproject.common.Result;
import com.study.forumsystemproject.common.ResultCode;
import com.study.forumsystemproject.model.LoginInfo;
import com.study.forumsystemproject.model.User;
import com.study.forumsystemproject.service.impl.UserImpl;
import com.study.forumsystemproject.utils.JwtUtil;
import com.study.forumsystemproject.utils.MD5Util;
import com.study.forumsystemproject.utils.UUidUtil;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * program: forum-system-project
 * <p>
 * description: 用户控制层
 * <p>
 * author: xiaoxie
 * <p>
 * create: 2024-08-15 18:20
 **/
@RequestMapping("/user")
@RestController
@Slf4j
@Tag(name = "用户类测试API")
public class UserController {
    @Autowired
    private UserImpl userImpl;
    @Operation(summary = "用户注册测试API")
    @PostMapping("/register")
    public Result<Boolean> register(@Schema(description = "注册的参数") @RequestBody User user) {
        log.info(user.toString());
        String uuid = UUidUtil.getUUID();
        String password = MD5Util.md5AndSalt(user.getPassword(),uuid);
        user.setPassword(password);
        String encryptPassword = MD5Util.md5AndSalt(user.getVerifyPassword(),uuid);
        user.setSalt(uuid);
        user.setVerifyPassword(encryptPassword);
        user.setGender(2);
        user.setArticleCount(0);
        user.setIsAdmin(0);
        user.setState(0);
        user.setDeleteFlag(0);
        userImpl.register(user);
        return Result.success(true);
    }
    @Operation(summary = "获取验证码")
    @GetMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) {
        userImpl.getCaptcha(session, response);
    }
    @Operation(summary = "用户登录的API")
    @PostMapping("/login")
    public Result<String> login(@Valid @RequestBody LoginInfo loginInfo,HttpSession session) {
        LoginInfo login = userImpl.login(loginInfo, session);
        if(login == null) {
            return Result.fail("登录失败");
        }
        Map<String,Object> claims = new HashMap<>();
        claims.put("username",login.getUsername());
        Long id =  login.getId();
        claims.put("UserId",id.longValue());
        claims.put("userState",login.getState());
        String jwt = JwtUtil.createJwt(claims);
        return Result.successJwt(jwt);
    }
    @Operation(summary = "获取用户信息的API")
    @PostMapping("/userInfo")
    public Result<User> getUser(HttpServletRequest request,
                                @Parameter(description = "用户ID",required = true)Long id) {
        //如果Id等于null 那么就使用Token的ID
        String userTokenHeader = request.getHeader("user_token_header");
        Claims claims = JwtUtil.verifyJwt(userTokenHeader);
        if(id == null) {

            id = ((Number) claims.get("UserId")).longValue();
        }
        User user = userImpl.getUserInfo(id);
        if(user == null) {
         log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
         return Result.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        user.setPassword(null);
        user.setSalt(null);
        user.setVerifyPassword(null);
        user.setDeleteFlag(null);
        //查询最新的用户信息
        return Result.success(user);
    }
    @Operation(summary = "更新用户信息的API")
    @PostMapping("/modifyInfo")
    public Result<User> modifyUser(HttpServletRequest request,String username,String nickname
            ,String phoneNum,String email,Integer gender, String avatarUrl,String remark) {
        Long userId = ((Number)JwtUtil.getValue(request,"UserId")).longValue();
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setEmail(email);
        updateUser.setGender(gender);
        updateUser.setAvatarUrl(avatarUrl);
        updateUser.setRemark(remark);
        userImpl.modifyUser(updateUser);
        User userInfo = userImpl.getUserInfo(userId);
        if(userInfo == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return Result.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return Result.success(userInfo);
    }
    @Operation(summary = "更新用户密码的API")
    @PostMapping("/modifyPwd")
    public Result<Boolean> modifyPassword(HttpServletRequest request,@NotNull String oldPassword
            ,@NotNull String newPassword,@NotNull String passwordRepeat) {
        Long userId = ((Number)JwtUtil.getValue(request,"UserId")).longValue();
        if(!newPassword.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return Result.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        userImpl.modifyPassword(userId,oldPassword,newPassword);
        return Result.success(true);
    }
}
